package com.simp.utils;

import com.simp.entity.SysLogEntity;
import com.simp.expection.GlobalException;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author pan.shun
 * @since 2022/3/8 09:08
 */
@Slf4j
public class BeanServiceUtils {

    /**
     * 通过反射来获取Bean组件
     *
     * @param serviceName Bean组件名称
     * @param methodName  方法名
     * @param paramsType  参数类型
     * @param paramsValue 入参值
     */
    private static Object createReflectBeanService(String serviceName, String methodName, Class[] paramsType, Object... paramsValue) {
        try {
            Object beanObject = SpringContextUtils.getBean(serviceName);
            Class<?> aClass = beanObject.getClass();
            Method method = aClass.getMethod(methodName, paramsType);
            return method.invoke(beanObject, paramsValue);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.error("通过反射构建{}组件失败，当前方法名:{} ,入参类型：{}，入参值：{}", serviceName, methodName, paramsType, paramsValue);
            throw new GlobalException("通过反射构建 [" + serviceName + "]组件失败");
        }
    }

    /**
     * 通过表名和数据源id 获取原始表对象
     */
    public static void saveLog(SysLogEntity sysLogEntity, Long startTime) {
        Object[] v = {sysLogEntity, startTime};
        createReflectBeanService("sysLogService", "saveAspectLog", new Class[]{SysLogEntity.class, Long.class}, v);
    }


}
